{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. # 使用 auto() 自动生成枚举值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from enum import Enum, IntEnum, auto\n",
    "\n",
    "class Weekday(IntEnum):\n",
    "    TUE = auto()\n",
    "    WED = auto()\n",
    "\n",
    "print(Weekday.TUE.value)  \n",
    "print(Weekday.WED.value)  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 自定义生成逻辑：重写 _generate_next_value_ 方法："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "pending_0\n"
     ]
    }
   ],
   "source": [
    "from enum import Enum, IntEnum, auto\n",
    "class CustomEnum(Enum):\n",
    "    def _generate_next_value_(name, start, count, last_values):\n",
    "        # 将 name 转换为字符串后再调用 lower()\n",
    "        return f\"{str(name).lower()}_{count}\"\n",
    "\n",
    "class Status(CustomEnum):\n",
    "    PENDING = auto()  # \"pending_1\"\n",
    "    APPROVED = auto() # \"approved_2\"\n",
    "\n",
    "print(Status.PENDING.value)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2. 枚举成员的元数据（附加属性）\n",
    "为枚举成员绑定额外数据（如描述、标签等）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "class HTTPStatus(Enum):\n",
    "    OK = (200, \"Success\")\n",
    "    NOT_FOUND = (404, \"Not Found\")\n",
    "\n",
    "    def __init__(self, code, desc):\n",
    "        self._value_ = code  # 必须赋值给 _value_\n",
    "        # 使用 _desc 作为私有属性名称来存储描述信息\n",
    "        self._desc = str(desc)    # 自定义私有属性\n",
    "\n",
    "print(HTTPStatus.OK._desc)  # 输出: \"Success\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "3. 枚举成员的迭代与比较\n",
    "遍历所有成员："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from enum import Enum\n",
    "\n",
    "class Color(Enum):\n",
    "    RED = 1\n",
    "    GREEN = 2\n",
    "    BLUE = 3\n",
    "print(\"Color Enum Members:\")\n",
    "for color in Color:\n",
    "    print(color)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "比较操作：\n",
    "\n",
    "身份比较：Color.RED is Color.RED（True）\n",
    "\n",
    "值比较：Color.RED == 1（需用 IntEnum 或显式比较 Color.RED.value == 1）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "4. 唯一性约束（@unique 装饰器）\n",
    "强制所有成员的值必须唯一："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from enum import Enum, unique\n",
    "\n",
    "@unique\n",
    "class Status(Enum):\n",
    "    ACTIVE = 1\n",
    "    INACTIVE = 2\n",
    "    # DUPLICATE = 1  # 会抛出 ValueError"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "5. 动态创建枚举类\n",
    "运行时动态生成枚举："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Animal.CAT\n"
     ]
    }
   ],
   "source": [
    "Animal = Enum('Animal', 'CAT DOG BIRD', start=10)\n",
    "print(Animal.CAT)  # 输出: Animal.CAT (值为 10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "6. 枚举的别名（Alias）\n",
    "允许不同名称指向同一个值（非 @unique 时）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "class Shape(Enum):\n",
    "    CIRCLE = 1\n",
    "    SQUARE = 2\n",
    "    ROUND = 1  # CIRCLE 的别名\n",
    "\n",
    "print(Shape.ROUND is Shape.CIRCLE)  # True"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "7. 枚举的方法与属性\n",
    "为枚举类添加方法："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Planet(Enum):\n",
    "    EARTH = (5.97e24, 6371)\n",
    "    MARS = (6.39e23, 3389)\n",
    "\n",
    "    def __init__(self, mass, radius):\n",
    "        self.mass = mass\n",
    "        self.radius = radius\n",
    "\n",
    "    @property\n",
    "    def surface_gravity(self):\n",
    "        return self.mass / (self.radius ** 2)\n",
    "\n",
    "print(Planet.EARTH.surface_gravity)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "8. 枚举的序列化与反序列化\n",
    "转换为字典/JSON："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "from enum import Enum\n",
    "\n",
    "class Status(Enum):\n",
    "    PENDING = \"pending\"\n",
    "    DONE = \"done\"\n",
    "\n",
    "# 自定义 JSON 编码器\n",
    "class EnumEncoder(json.JSONEncoder):\n",
    "    def default(self, obj):\n",
    "        if isinstance(obj, Enum):\n",
    "            return obj.value\n",
    "        return super().default(obj)\n",
    "\n",
    "json.dumps(Status.PENDING, cls=EnumEncoder)  # 输出: '\"pending\"'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "从值恢复枚举："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Status(\"pending\")  # 返回 Status.PENDING"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "9. 枚举的组合与扩展\n",
    "Flag 枚举：支持位运算（如权限控制）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from enum import Flag, auto\n",
    "\n",
    "class Permissions(Flag):\n",
    "    READ = auto()\n",
    "    WRITE = auto()\n",
    "    EXECUTE = auto()\n",
    "\n",
    "user_perms = Permissions.READ | Permissions.WRITE\n",
    "print(Permissions.READ in user_perms)  # True\n",
    "print(Permissions.EXECUTE in user_perms)  # False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "10. 枚举的模式匹配（Python 3.10+）\n",
    "在 match-case 中使用枚举："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "match HTTPStatus.OK:\n",
    "    case HTTPStatus.OK:\n",
    "        print(\"Success!\")\n",
    "    case HTTPStatus.NOT_FOUND:\n",
    "        print(\"Not Found\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
